<template>
	<view class="pageBg">
		<Skeleton v-if="skeletonLoading" type="index"></Skeleton>
		<Head ref="head" title="首页" type="index" :isBack="false"></Head>
		<view class="indexWrapper">
			<!-- 菜单 -->
			<IndexMenu :dataset="menu_list"></IndexMenu>
			<!-- 菜单 -->
			<!-- 公告 -->
			<IndexNotice :dataset="notice_list"></IndexNotice>
			<!-- 公告 -->
			<!-- 广告位 -->
			<view class="indexAd">
				<!-- 后台需要添加 -->
				<swiper class="adSwiper" :autoplay="true">
					<!-- 头部轮播 -->
					<swiper-item class="adSwiperItem" v-for="(item,index) in ad_dataset_top.items" :key="index">
						<image class="img" :src="item.image_src" @click="handleBannerJump(item)"></image>
					</swiper-item>
				</swiper>
			</view>
			<!-- 广告位 -->
			<!-- 列表切换 -->
			<view class="indexList">
				<view class="tabBtnsBox">
					<view class="tabBtns">
						<!-- 推荐 一周以内的点击量倒序 -->
						<view :class="currentTabBtn == 1 ? 'tabBtn ac' : 'tabBtn'" @click="handleTabSwitch(1)">推荐</view>
						<!-- 最新 时间排序 -->
						<view :class="currentTabBtn == 2 ? 'tabBtn ac' : 'tabBtn'" @click="handleTabSwitch(2)">最新</view>
						<!-- 附近 经纬度计算  -->
						<view v-if="LoginType == 2" :class="currentTabBtn == 3 ? 'tabBtn ac' : 'tabBtn'"
							@click="handleTabSwitch(3)">附近</view>
					</view>
					<view class="more" @click="handleJumpList">查看更多</view>
				</view>
				<view class="tabCon">
					<view>
						<view v-if="LoginType == 0 || LoginType == 2">
							<template v-if="jobList.length>0">
								<jobItem v-for="(item,index) in jobList" :key="index" :item="item" @toDetail="toDetail">
								</jobItem>
								<u-loadmore v-if="jobList.length >= pagesize" class="u-loadmore"
									:status="finished_status"></u-loadmore>
							</template>
							<Empty v-if="show_empty"></Empty>
						</view>
						<view v-if="LoginType == 1">
							<template v-if="resumeList.length>0">
								<resumeItem v-for="(item,index) in resumeList" :key="index" :item="item"
									@toDetail="toResumeShowDetail"></resumeItem>
								<u-loadmore v-if="resumeList.length >= pagesize" class="u-loadmore"
									:status="finished_status"></u-loadmore>
							</template>
							<Empty v-if="show_empty"></Empty>
						</view>
					</view>
				</view>
			</view>
			<!-- 列表切换 -->
		</view>
		<!-- 未授权弹窗 -->
		<Popup ref="authPopup" @confirm="handleAuthConfirm">
			<view style="padding:20rpx 0;">{{auth.text}}</view>
		</Popup>
		<IndexNoLoginTips v-if="LoginType == 0"></IndexNoLoginTips>
		<!-- 隐私政策弹窗 -->
		<Privacypolicy ref="refPrivacypolicy" @openRefusePrivacypolicy="openRefusePrivacypolicy"
			:sitename="config.sitename" :privacyContractName="privacyContractName"></Privacypolicy>
		<PrivacypolicyStep2 ref="refPrivacypolicyStep2" :privacyContractName="privacyContractName"
			:sitename="config.sitename">
		</PrivacypolicyStep2>
		<BottomNav></BottomNav>
	</view>
</template>

<script>
	import http from '@/utils/http'
	import api from '@/api'
	import {
		gcToDb
	} from '@/utils/map.js'
	// 新版
	import IndexMenu from '../components/index/Menu.vue'
	import IndexNotice from '../components/index/Notice.vue'
	import jobItem from '@/components/listItem/jobItem.vue'
	import resumeItem from '@/components/listItem/resumeItem.vue'
	import IndexNoLoginTips from '@/components/index/NoLoginTips.vue'
	import Skeleton from '@/components/Skeleton.vue'
	import Head from '@/components/Head.vue'
	import Privacypolicy from '@/components/Privacypolicy.vue'
	import PrivacypolicyStep2 from '@/components/PrivacypolicyStep2.vue'
	import {
		mapState
	} from 'vuex'
	import {
		onShareAppMessage,
		onShareTimeline
	} from '@/utils/share.js'
	import {
		changeIsAuth
	} from '@/utils/uni.js'
	export default {
		name: 'Index',
		data() {
			return {
				auth: {
					text: '',
					authText: '',
					isAuth: ''
				},
				finished_status: 'loadmore',
				skeletonLoading: true,
				empytSrc: require('../static/img/empty.png'),
				currentTabBtn: 1,
				menu_list: [{
						id: 1,
						children: [{
								alias: 'resume',
								title: '找人才',
								icon: '',
								url: ''
							}, {
								alias: 'job',
								title: '找工作',
								icon: '',
								url: ''
							},
							{
								alias: 'company',
								title: '搜企业',
								icon: '',
								url: ''
							}, {
								alias: 'urgent',
								title: '急聘专区',
								icon: '',
								url: ''
							},
							{
								alias: 'famous',
								title: '名企直聘',
								icon: '',
								url: ''
							}
						]
					},
					{
						id: 2,
						children: [{
								alias: 'jobfairs',
								title: '招聘会',
								icon: '',
								url: ''
							},
							{
								alias: 'article',
								title: '新闻资讯',
								icon: '',
								url: ''
							},
							// {
							// 	alias: 'map',
							// 	title: '附近职位',
							// 	icon: '',
							// 	url: ''
							// }
						]
					}


				],
				notice_list: [],
				ad_dataset_top: {
					alias: 'QS_top_slide',
					items: []
				},
				ad_dataset_banner_a: {
					alias: 'QS_index_banner_a',
					items: []
				},
				ad_dataset_banner_b: {
					alias: 'QS_index_banner_b',
					items: []
				},
				jobList: [],
				resumeList: [],
				selectArrOnload: [],
				selectResumeArrOnload: [],
				page: 1,
				pagesize: 10,
				show_empty: false,
				privacyContractName: ''
			}
		},
		components: {
			// 新版
			IndexMenu,
			IndexNotice,
			jobItem,
			resumeItem,
			IndexNoLoginTips,
			Skeleton,
			Head,
			Privacypolicy,
			PrivacypolicyStep2
		},
		mounted() {
			// #ifdef MP-WEIXIN
			let todayTimestampStorage = uni.getStorageSync('todayTimestamp')
			let now = new Date().setHours(0, 0, 0, 0); // 创建一个 Date 对象，表示当前时间。将时、分、秒、毫秒设置为零，只保留日期部分
			let todayTimestamp = Math.floor(now / 1000); // 获取当前日期的时间戳（精确到秒）
			uni.setStorageSync('todayTimestamp', todayTimestamp)
			wx.getPrivacySetting({
				success: res => {
					this.privacyContractName = res.privacyContractName
					if (todayTimestampStorage != todayTimestamp) {
						this.$refs.refPrivacypolicy.open()
					}
				},
				fail: () => {},
				complete: () => {}
			})
			// #endif
		},
		onPageScroll(res) {
			uni.$emit('onPageScroll', res.scrollTop)
		},
		onReachBottom() {
			this.finished_status = 'loading';
			this.page++
			if (this.LoginType == 0 || this.LoginType == 2) {
				this.getJobData({
					sort: 'click'
				}, false)
			} else {
				this.getResmueData({}, false)
			}
		},
		onLoad() {},
		onShareAppMessage() {
			return onShareAppMessage({
				url: '/views/Index',
				alias: "index",
				info: {}
			})
		},
		onShareTimeline() {
			info.imgUrl = this.info.thumb
			return onShareTimeline({
				url: '/views/index',
				alias: "index",
				info: {}
			})
		},
		onReady() {
			this.initModule()
			this.fetchAd()
			if (this.LoginType == 0 || this.LoginType == 2) {
				this.getJobData({
					sort: 'click'
				}, true)
			} else {
				this.getResmueData({}, true)
			}
			this.cronRun()
			uni.login({
				scopes: 'auth_base',
				success: function(res) {
					// console.log(res)
				},
				fail: function(err) {
					console.log(err)
				}
			})
		},
		computed: {
			...mapState(['LoginType', 'config'])
		},
		methods: {
			openRefusePrivacypolicy(val) {
				console.log(val, '点击拒绝同意隐私第一步')
				if (val) {
					this.$refs.refPrivacypolicyStep2.open()
				}
			},
			handleAuthConfirm() {
				var {
					authText,
					isAuth
				} = this.auth
				if (authText == 'gps') {
					this.$refs.authPopup.close()
					// this.changeIsAuth()
				} else if (authText == 'setting') {
					uni.openSetting({
						success: (res) => {}
					})
				}
			},
			handleJumpList() {
				if (this.LoginType == 0 || this.LoginType == 2) {
					// jobList
					uni.navigateTo({
						url: '/views/JobList'
					})
				} else if (this.LoginType == 1) {
					// resumeList
					uni.navigateTo({
						url: '/views/ResumeList'
					})
				}
			},
			getColorChange() {
				let LoginOrNotLocal = uni.getStorageSync('LoginOrNot');
				let LoginOrNot = this.$store.state.LoginOrNot.toString();
				uni.setStorageSync('LoginOrNot', LoginOrNot); //更新缓存中登录状态
				if (LoginOrNot != LoginOrNotLocal) { //登录状态改变时清空缓存数据
					uni.setStorageSync('selectArr', null); //职位
					uni.setStorageSync('selectResumeArr', null); //简历 
					uni.setStorageSync('selectComArr', null); //企业
				}
				this.selectResumeArrOnload = uni.getStorageSync('selectResumeArr') == null || uni.getStorageSync(
					'selectResumeArr') == '' || uni.getStorageSync(
					'selectResumeArr') == undefined ? [] : JSON.parse(uni.getStorageSync('selectResumeArr'))
				this.selectResumeArrOnload.forEach(items => {
					this.resumeList.forEach(item => {
						if (item.id == items) {
							item.clicked = true
						}
					})
				})
			},
			toResumeShowDetail(id) {
				let selectResumeArr = this.selectResumeArrOnload == undefined ? [] : this.selectResumeArrOnload
				if (selectResumeArr.indexOf(id) == -1) {
					selectResumeArr.push(id)
				}
				let selectResumeArrStr = JSON.stringify(selectResumeArr)
				uni.setStorageSync('selectResumeArr', selectResumeArrStr)
				for (let i in this.resumeList) {
					if (this.resumeList[i].id == id && !this.resumeList[i].clicked) {
						this.resumeList[i].clicked = true
					}
				}
				uni.navigateTo({
					url: '/commonViews/ResumeShow?id=' + id
				})
			},
			toDetail(id) {
				let selectArr = uni.getStorageSync('selectArr')
				selectArr = selectArr == 'null' || selectArr == null || selectArr == '' ? [] : JSON.parse(selectArr)
				if (selectArr.indexOf(id) == -1 || selectArr.length == 0) {
					selectArr.push(id)
				}
				this.selectArrOnload = selectArr
				uni.setStorageSync('selectArr', JSON.stringify(selectArr))
				for (let i in this.jobList) {
					if (this.jobList[i].id == id) {
						this.jobList[i].clicked = true
					}
				}
				console.log('跳转职位详情')
				uni.navigateTo({
					url: '/commonViews/JobShow?id=' + id
				})
			},
			initModule() {
				http
					.get(api.index_common, {})
					.then(res => {
						const {
							data
						} = res.data.data
						const {
							notice_list
						} = data
						this.notice_list = notice_list
					})
					.catch(() => {})
			},
			fetchAd() {
				http
					.post(api.ad_list, {
						alias: [
							'QS_top_slide@miniprogram',
							'QS_index_banner_a@miniprogram',
							'QS_index_banner_b@miniprogram',
							'QS_member_company_banner@miniprogram',
							'QS_member_personal_banner@miniprogram'
						]
					})
					.then(res => {
						this.ad_dataset_top.items = res.data.data.items['QS_top_slide@miniprogram']
						this.ad_dataset_banner_a.items = res.data.data.items['QS_index_banner_a@miniprogram']
						this.ad_dataset_banner_b.items = res.data.data.items['QS_index_banner_b@miniprogram']
					})
					.catch(() => {})
			},
			cronRun() {
				http
					.get(api.cron_run)
					.then(() => {})
					.catch(() => {})
			},
			// 获取职位数据
			getJobData(data, init) {
				if (init) {
					this.jobList = []
				}
				var params = {
					page: this.page,
					pagesize: this.pagesize,
					...data
				}
				this.show_empty = false
				http
					.get(api.joblist, params)
					.then(res => {
						if (init == true) {
							this.jobList = [...res.data.data.items]
						} else {
							this.jobList = this.jobList.concat(res.data.data.items)
						}
						// 判断用户是否点击查看过某些数据
						if (this.selectArrOnload.length > 0) {
							for (let j in this.selectArrOnload) {
								for (let i in this.jobList) {
									if (this.jobList[i].id == this.selectArrOnload[j]) {
										this.jobList[i].clicked = true
									} else {
										this.jobList[i].clicked = false
									}
								}
							}
						} else {
							for (let i in this.jobList) {
								this.jobList[i].clicked = false
							}
						}
						this.skeletonLoading = false

						this.finished_status = 'loading';
						// 数据全部加载完成
						if (res.data.data.items.length <= this.pagesize) {
							this.finished_status = 'nomore'
							if (init === false) {
								this.finished_status = 'nomore'
							} else if (res.data.data.items.length === 0) {
								this.show_empty = true
								this.finished_status = 'nomore'
							}
						}

					})
					.catch(() => {})
			},
			// 获取简历数据
			getResmueData(data, init) {
				if (init) {
					this.resumeList = []
				}
				var params = {
					page: this.page,
					pagesize: this.pagesize,
					...data
				}
				this.show_empty = false
				http
					.get(api.resumelist, params)
					.then(res => {
						if (init) {
							this.resumeList = [...res.data.data.items]
						} else {
							this.resumeList = this.resumeList.concat(res.data.data.items)
						}

						this.skeletonLoading = false
						this.resumeList.forEach(item => {
							item.clicked = false
						})
						this.getColorChange(); //缓存数据标题是否变色

						this.finished_status = 'loading';
						// 数据全部加载完成
						if (res.data.data.items.length <= this.pagesize) {
							this.finished_status = 'nomore'
							if (init === false) {
								this.finished_status = 'nomore'
							} else if (res.data.data.items.length === 0) {
								this.show_empty = true
								this.finished_status = 'nomore'
							}
						}

					})
					.catch(() => {})
			},
			getColorChange() {
				let LoginOrNotLocal = uni.getStorageSync('LoginOrNot');
				let LoginOrNot = this.$store.state.LoginOrNot.toString();
				uni.setStorageSync('LoginOrNot', LoginOrNot); //更新缓存中登录状态
				if (LoginOrNot != LoginOrNotLocal) { //登录状态改变时清空缓存数据
					uni.setStorageSync('selectArr', null); //职位
					uni.setStorageSync('selectResumeArr', null); //简历 
					uni.setStorageSync('selectComArr', null); //企业
				}
				this.selectResumeArrOnload = uni.getStorageSync('selectResumeArr') == null || uni.getStorageSync(
					'selectResumeArr') == '' || uni.getStorageSync(
					'selectResumeArr') == undefined ? [] : JSON.parse(uni.getStorageSync('selectResumeArr'))
				this.selectResumeArrOnload.forEach(items => {
					this.resumeList.forEach(item => {
						if (item.id == items) {
							item.clicked = true
						}
					})
				})
			},
			// tab切换
			handleTabSwitch(type) {
				// 1 企业 2个人
				if (this.LoginType == 1) { // 企业
					this.switchReumsTab(type)
				} else if (this.LoginType == 2) { // 个人
					this.switchJobTab(type)
				} else {
					this.switchJobTab(type)
				}
			},
			// 职位切换
			async switchJobTab(type) {
				this.page = 1
				if (type == 1) { // 推荐
					this.getJobData({
						sort: 'click'
					}, true)
					this.currentTabBtn = type
				} else if (type == 2) { // 最新
					this.getJobData({
						sort: 'rtime'
					}, true)
					this.currentTabBtn = type
				} else if (type == 3) { //附近职位 
					let {
						auth,
						isAuth,
						isGps,
						location
					} = await changeIsAuth('location')
					if (!isGps) {
						//gps权限没有开启 提示用户开启权限
						this.auth.text = '请打开定位服务功能'
						this.auth.authText = 'gps'
						this.auth.isAuth = isGps
						this.$refs.authPopup.open()
					} else if (!isAuth) {
						this.auth.text = '请允许使用位置信息'
						this.auth.authText = 'setting'
						this.auth.isAuth = isAuth
						this.$refs.authPopup.open()
					} else {
						var localtion2 = gcToDb(location.latitude, location.longitude)
						this.getJobData(localtion2, true)
					}
					if (isAuth) {
						this.currentTabBtn = type
					}
				}
			},
			handleBannerJump(item) {
				if (item.link_url) {
					uni.navigateTo({
						url: item.link_url
					})
				} else if (item.company_id > 0) {
					uni.navigateTo({
						url: '/commonViews/CompanyShow?id=' + item.company_id
					})
				} else if (item.inner_link) {
					let path = ''
					let params_type = 'query'
					/**
					 * 首页  /views/Index
					 * 职位列表页 /views/JobList
					 * 职位详情页 /commonViews/JobShow
					 * 简历列表页 /views/ResumeList
					 * 资讯列表页 /commonViews/News
					 * 资讯详情页 /commonViews/NewShow
					 * 公告详情页 /commonViews/NoticeShow
					 * */
					switch (item.inner_link) {
						case 'index':
							path = '/views/Index'
							break
						case 'joblist':
							path = '/views/JobList'
							break
						case 'jobshow':
							path = '/commonViews/JobShow'
							params_type = 'params'
							break
						case 'resumelist':
							path = '/views/ResumeList'
							break
						case 'noticeshow':
							path = '/commonViews/NoticeShow'
							params_type = 'params'
							break
						case 'articlelist':
							path = '/commonViews/News'
							break
						case 'articleshow':
							path = '/commonViews/NewShow'
							params_type = 'params'
							break
						default:
							path = ''
							break
					}
					if (path != '') {
						if (item.inner_link_params > 0) {
							if (params_type == 'params') {
								path = path + '?id=' + item.inner_link_params
							}
						}
						uni.navigateTo({
							url: path
						})
					}
				}
			},
			// 简历切换
			async switchReumsTab(type) {
				this.page = 1
				if (type == 1) { // 推荐
					this.getResmueData({}, true)
					this.currentTabBtn = type
				} else if (type == 2) { // 最新
					this.getResmueData({
						sort: 'rtime'
					}, true)
					this.currentTabBtn = type
				} else if (type == 3) { //附近职位 
					let {
						auth,
						isAuth,
						isGps,
						location
					} = await changeIsAuth('location')
					if (!isGps) {
						//gps权限没有开启 提示用户开启权限
						this.auth.text = '请打开定位服务功能'
						this.auth.authText = 'gps'
						this.auth.isAuth = isGps
						this.$refs.authPopup.open()
					} else if (!isAuth) {
						this.auth.text = '请允许使用位置信息'
						this.auth.authText = 'setting'
						this.auth.isAuth = isAuth
						this.$refs.authPopup.open()
					} else {
						var localtion2 = gcToDb(location.latitude, location.longitude)
						this.getResmueData(localtion2, true)
					}
					if (isAuth) {
						this.currentTabBtn = type
					}
				}
			}
		}
	}
</script>

<style lang="scss" scoped>
	.indexWrapper {
		/* #ifdef MP-TOUTIAO || MP-ALIPAY || MP-ALIPAY */
		padding: 0 30rpx 0;
		/* #endif */
		/* #ifdef MP-WEIXIN */
		padding: 30rpx 30rpx 0;
		/* #endif */
	}

	// 广告位 
	.indexAd {
		height: 240rpx;
		border-radius: 15rpx;
		overflow: hidden;
		margin-top: 20rpx;
		margin-bottom: 20rpx;

		.adSwiper {
			width: 100%;
			height: 100%;

			.adSwiperItem {
				width: 100%;
				height: 100%;
				border-radius: 14rpx;
				overflow: hidden;
			}
		}

		image {
			width: 100%;
			height: 100%;
			display: block;
		}
	}

	// 广告位

	// 首页列表
	.indexList {
		.tabBtnsBox {
			display: flex;
			justify-content: space-between;
			padding: 20rpx 0 30rpx;

			.tabBtns {
				display: flex;
				align-items: center;

				.tabBtn {
					color: #999999;
					font-size: 30rpx;
					padding: 0 21rpx;

					&.ac {
						font-weight: bold;
						color: #2a2a2a;
						font-size: 36rpx;
					}
				}
			}

			.more {
				color: #6799ff;
				font-size: 26rpx;
			}
		}

		.tabCon {}
	}

	// 首页列表



	.ba {
		image {
			width: 100%;
			height: 126rpx;
		}

		width: 100%;
		height: 126rpx;
		margin-bottom: 18rpx;
	}
</style>